// pages/exp/double/result.js
var utils = require('../../../utils/util.js')
var stat = require('../../../utils/stat.js')
import * as echarts from '../../../ec-canvas/echarts';

function initScatterPlot(chart, treatedScores, untreatedScores, meanTreatedScore, meanUntreatedScore) {
    console.log(treatedScores, untreatedScores, meanTreatedScore, meanUntreatedScore)
    var index = 1;
    var treatedPoints = [];
    for (var i in treatedScores) {
        treatedPoints.push([parseInt(treatedScores[i]), index]);
        index++;
    }
    var untreatedPoints = [];
    for (var i in untreatedScores) {
        untreatedPoints.push([parseInt(untreatedScores[i]), index]);
        index++;
    }
    const option = {
        title: {
            x: 'center',
            text: '图1.水结晶实验评分结果散点图',
            subtext: '虚线为两类水样照片评分的均值'
        },
        legend: {
            y: 'bottom',
            data: ['用意念处理过的', '未用意念处理的']
        },
        animation: false,
        backgroundColor: '#eee',
        color: ['#f30', '#009'],
        xAxis: [{
            type: 'value',
            name: '评分'
        }],
        yAxis: [{
            type: 'value',
            name: '照片编号(乱序)'
        }],
        series: [
            {
                name: '用意念处理过的',
                type: 'scatter',
                data: treatedPoints,
                markLine: {
                    silent: true,
                    precision: 3,
                    symbol: 'none',
                    lineStyle: {
                        normal: {
                            type: 'dash'
                        }
                    },
                    data: [
                        [
                            {
                                name: meanTreatedScore,
                                xAxis: meanTreatedScore,
                                valueIndex: 1,
                                y: '12%'
                            }, {
                                xAxis: meanTreatedScore,
                                valueIndex: 1,
                                y: '90%'
                            }
                            // { xAxis: meanTreatedScore, yAxis: -1, value: meanTreatedScore },
                            // { name: '均值:', xAxis: meanTreatedScore, yAxis: 40 }
                        ]
                    ]
                }
            },
            {
                name: '未用意念处理的',
                type: 'scatter',
                data: untreatedPoints,
                markLine: {
                    silent: true,
                    precision: 3,
                    symbol: 'none',
                    lineStyle: {
                        normal: {
                            type: 'dash'
                        }
                    },
                    data: [
                        [
                            {
                                name: meanUntreatedScore,
                                xAxis: meanUntreatedScore,
                                valueIndex: 1,
                                y: '12%'
                            }, {
                                xAxis: meanUntreatedScore,
                                valueIndex: 1,
                                y: '90%'
                            }
                            // { xAxis: meanUntreatedScore, yAxis: -1, value: meanUntreatedScore },
                            // { name: '均值:', xAxis: meanUntreatedScore, yAxis: 40 }
                        ]
                    ]
                }
            }
        ]
    };
    chart.setOption(option);
}

function initFreqChart(chart, frequencyTreatedScores, frequencyUntreatedScores) {
    console.log(frequencyTreatedScores, frequencyUntreatedScores )
    chart.setOption({
        title: {
            x: 'center',
            text: '图2.水结晶实验评分频率分布',
            subtext: '评分频率为分组归一化后的结果'
        },
        animation: false,
        legend: {
            y: 'bottom',
            data: ['用意念处理过的', '未用意念处理的']
        },
        backgroundColor: '#eee',
        color: ['#f30', '#009'],
        xAxis: [{
            type: 'category',
            name: '评分',
            data: [0, 1, 2, 3, 4, 5, 6]
        }],
        yAxis: [{
            type: 'value',
            name: '评分频率'
        }],
        series: [
            {
                name: '用意念处理过的',
                type: 'bar',
                barMaxWidth: 20,
                data: frequencyTreatedScores
            },
            {
                name: '未用意念处理的',
                type: 'bar',
                barMaxWidth: 20,
                data: frequencyUntreatedScores
            }
        ]
    });
    return chart;
}

Page({

    /**
     * 页面的初始数据
     */
    data: {
        pValue: '&le;0.025',
        meanDiff: 1.0830,
        df: 31,
        ec: {
            lazyLoad: true // 将 lazyLoad 设为 true 后，需要手动初始化图表
        },
        ec1: {
            lazyLoad: true
        }
    },

    // 点击按钮后初始化图表
    initCharts: function (treatedScores, untreatedScores, meanTreatedScore, meanUntreatedScore, frequencyTreatedScores, frequencyUntreatedScores) {

        this.ecComponent.init((canvas, width, height) => {
            // 获取组件的 canvas、width、height 后的回调函数
            // 在这里初始化图表
            //   console.log(width, height)
            //   return initChart(canvas, width, height);
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            initScatterPlot(chart, treatedScores, untreatedScores, meanTreatedScore, meanUntreatedScore);
            // 注意这里一定要返回 chart 实例，否则会影响事件处理等
            return chart;
        });

        this.ecComponent1.init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            initFreqChart(chart, frequencyTreatedScores, frequencyUntreatedScores);
            return chart;
        });

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        wx.showNavigationBarLoading()
        var aid = options.attendID
        const that = this;
        utils.httpRequest({
            url: '/OrderedExp/doubleResult',
            data: { attendID: aid },
            success: function (res) {
                // console.log("from user call",res.data)
                wx.hideNavigationBarLoading()
                var data = res.data
                var statResult = stat.tTest(data.treated, data.untreated)
                var count = data.treated.length + data.untreated.length
                that.setData({
                    pValueSign: statResult[0][0],
                    pValue: statResult[0][1],
                    isSignificant: statResult[0][1] <= 0.05 && statResult[0][0] == '≤',
                    meanDiff: statResult[2],
                    df: statResult[1],
                    treated: statResult[3],
                    untreated: statResult[4],
                    begin_t: data.begin_t,
                    end_t: data.end_t,
                    count: count,
                    isOwner: data.is_owner,
                    read_count: data.read_count,
                })
                that.initCharts(stat.str2int(data.treated), stat.str2int(data.untreated), parseFloat(statResult[3]), parseFloat(statResult[4]), stat.count2frequency(data.treated), stat.count2frequency(data.untreated));
                var adjP = stat.adjustP(data.treated, data.untreated, 1000)
                that.setData({
                    adjPValue: adjP,
                    isAdjSignificant: adjP <= 0.05,
                    twoValueDiffSmall: Math.abs(adjP - statResult[0][1])<0.05,
                })
            }
        })
    },



    downloadAndViewDoubleTestPDF: function () {
        wx.getNetworkType({
            success: function (res) {
                // 返回网络类型, 有效值：
                // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
                var networkType = res.networkType
                //   if (networkType == 'wifi') {
                //       utils.downloadAndOpen('https://cdn.water-crystal.org/pdf/doubleCN.pdf');
                //   } else 
                if (networkType == 'none') {

                } else {
                    wx.showModal({
                        title: '查看中文文献？',
                        content: '查看此文档(PDF格式)需要消耗约0.5MB流量',
                        success: function (res) {
                            if (res.confirm) utils.downloadAndOpen('https://cdn.water-crystal.org/pdf/doubleCN.pdf');
                        }
                    })
                }
            }
        })

    },

    downDoubleEn: function () {
        wx.getNetworkType({
            success: function (res) {
                // 返回网络类型, 有效值：
                // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
                var networkType = res.networkType
                //   if (networkType == 'wifi') {
                //       utils.downloadAndOpen('https://cdn.water-crystal.org/pdf/doubleEN.pdf');
                //   } else 
                if (networkType == 'none') {

                } else {
                    wx.showModal({
                        title: '查看英文文献？',
                        content: '查看此文档(PDF格式)需要消耗约0.2MB流量',
                        success: function (res) {
                            if (res.confirm) utils.downloadAndOpen('https://cdn.water-crystal.org/pdf/doubleEN.pdf');
                        }
                    })
                }
            }
        })
    },

    myExps: function () {
        wx.redirectTo({
            url: '/pages/exp/exp', complete: function (r) { console.log(r) }
        })
    },

    gotoIndex: function () {
        wx.redirectTo({
            url: '/pages/index/index', complete: function (r) { console.log(r) }
        })
    },

    onPullDownRefresh: function () { wx.stopPullDownRefresh() },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return { title: "意念影响水：双盲实验报告", imageUrl: 'https://cdn.water-crystal.org/result.png' }
    },

    onReady: function () {
        // 获取组件
        this.ecComponent = this.selectComponent('#mychart-dom-bar');
        this.ecComponent1 = this.selectComponent('#mychart-dom-bar1');
    },
})